package com.unbox.common.configuration.exception;
import com.unbox.common.response.UnboxResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
@Log4j2
public class UnboxGlobalExceptionHandler {

    /**
     * 拦截普遍全局异常
     * @param request
     * @param response
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)//指定拦截的异常
    @ResponseBody
    public Object allErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception{
        log.error(e.getMessage());
        return new UnboxResponse.Builder<>().serviceFail();
    }

    /**
     * 拦截注解验证异常
     * @param request
     * @param response
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = UnboxAnnotionException.class)
    @ResponseBody
    public Object annoationErrorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception{
        log.error(e.getMessage());
        return new UnboxResponse.Builder<>().businessFail(e.getMessage());
    }
}
